package com.ship.dispatch.service.fob.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ship.common.core.utils.StringUtils;
import com.ship.dispatch.bean.SpArrangeSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bpm.service.TaskService;
import com.ship.dispatch.bpm.utils.CalculateDateUtil;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.mapper.fob.SpFobReturnSalesZzwjMapper;
import com.ship.dispatch.mapper.fob.SpFobSyzlzzwjMapper;
import com.ship.dispatch.service.SpArrangeSchemeDetailService;
import com.ship.dispatch.service.SpDispatchSchemeDetailService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpFobReturnSalesZzwjService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yl
 * @title SpFobReturnSalesZzwjServiceImpl
 * @description 003.FOB返装销售-船舶装载并制作装载文件
 * @create 2024/1/6 0006
 */
@Service
public class SpFobReturnSalesZzwjServiceImpl extends FobBaseServiceImpl<SpFobReturnSalesZzwjMapper, SpFobReturnSalesZzwj> implements SpFobReturnSalesZzwjService {
    @Autowired(required = false)
    SpFobReturnSalesZzwjMapper mapperapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;

    @Autowired
    SpFobTemplateService spFobTemplateService;
    @Autowired
    SpArrangeSchemeDetailService spArrangeSchemeDetailService;

    @Autowired
    @Lazy
    private SpDispatchSchemeDetailService spDispatchSchemeDetailService;

    @Autowired
    private TaskService taskService;
    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobReturnSalesZzwj object = JsonUtils.jsonToObject(json,SpFobReturnSalesZzwj.class);
        SpFobReturnSalesZzwj his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesZzwj>().eq(SpFobReturnSalesZzwj::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobReturnSalesZzwj::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);

        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            mapperapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            BeanUtils.copyProperties(object,his);
            mapperapper.updateById(his);
            // 处理多余文件记录
            List<String> ids = new ArrayList<>();
            his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesZzwj>().eq(SpFobReturnSalesZzwj::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobReturnSalesZzwj::getStatus,-2));
            if((his.getFiels()!=null && his.getFiels().length()>0)){
                String temp = his.getFiels();
                String[] fieldIds = temp.split(",");
                List<String> tempIds =  Arrays.stream(fieldIds).collect(Collectors.toList());
                ids.addAll(tempIds);
                // spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
            }
            if((his.getZzFile()!=null && his.getZzFile().length()>0)){
                String temp = his.getZzFile();
                String[] fieldIds = temp.split(",");
                List<String> tempIds =  Arrays.stream(fieldIds).collect(Collectors.toList());
                ids.addAll(tempIds);
                //
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
        if(manageEntityVo.getOperationType()==1 && object.getOnLoadDate()!=null) { // 完成任务 更新方案表实际装载实际
            SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
            SpArrangeSchemeDetail spDispatchSchemeDetail = new SpArrangeSchemeDetail();
            spDispatchSchemeDetail.setId(execute.getArrangeSchemeDetailId());
            spDispatchSchemeDetail.setRealityLoadingDate(object.getOnLoadDate());
            spArrangeSchemeDetailService.updateById(spDispatchSchemeDetail);
            spDispatchSchemeDetailService.update(
                    new LambdaUpdateWrapper<SpDispatchSchemeDetail>()
                            .set(SpDispatchSchemeDetail::getRealityLoadingDate,object.getOnLoadDate())
                            .eq(SpDispatchSchemeDetail::getArrangeSchemeDetailId,execute.getArrangeSchemeDetailId())
            );
            execute.setRealityLoadingDate(object.getOnLoadDate());
            schemeDetailService.updateById(execute);
            if(manageEntityVo.getTaskId()!=null){
                Map<String,Object> valible = new HashMap<>();
                valible.put("realityLoadingDate", CalculateDateUtil.pasrseDate(object.getOnLoadDate()));
                taskService.addVaribals(valible,manageEntityVo.getTaskId());
            }

        }
    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesZzwj>().eq(SpFobReturnSalesZzwj::getProceeInstanceId,id).ne(SpFobReturnSalesZzwj::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobReturnSalesZzwj spFob = new SpFobReturnSalesZzwj();
        BeanUtils.copyProperties(bean,spFob);
        this.save(spFob);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobReturnSalesZzwj spFob = new SpFobReturnSalesZzwj();
        BeanUtils.copyProperties(bean,spFob);
        this.updateById(spFob);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobReturnSalesZzwj spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = mapperapper.selectById(serviceId);
        }else {
            spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesZzwj>().eq(SpFobReturnSalesZzwj::getProceeInstanceId,id).ne(SpFobReturnSalesZzwj::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        if(spFobZzgcjr.getZzFile()!=null){
            String[] ids = spFobZzgcjr.getZzFile().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("zzFile",spFobFileRecordList);
        }
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if (execute.getExpectedLoadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedLoadingPort());
        }
        return map;
    }

    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobReturnSalesZzwj> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobReturnSalesZzwj>().eq(SpFobReturnSalesZzwj::getProceeInstanceId,processInstanceId).orderByDesc(SpFobReturnSalesZzwj::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }
}
